<?php

namespace App\Repository\XhApi;

use App\Models\Product\GoodsModel;
use App\Models\Product\ProductModel;
use App\Models\Product\SetAddressModel;
use App\Models\Xh\PhonesModel;
use App\Repository\BaseRepository;
use Illuminate\Support\Facades\Cache;

class GoodsRepository extends BaseRepository
{
    public $model;

    public function __construct()
    {
        $this->model = new GoodsModel();
        parent::__construct();
    }

    public function index($params, $page = 1, $limit = 10)
    {
        //查询商品列表
        if ($params['list_type'] == 1) {
            return $this->goodsList($params, $page, $limit);
        } else {
            return $this->searchNumber($params, $page, $limit);
        }
    }

    public function goodsList($params, $page = 1, $limit = 10)
    {
        $where = [];
        $where['eq']['xh_status'] = 0;
        //先要总数
        $totalRows = 0;
        if ($page == 1) {
            $totalRows = $this->model->searchWhere($where)->count('id');
        }
        $fields = ['id', 'main_pic', 'oblong_pic', 'name', 'goods_price', 'monthly', 'flow', 'voice', 'tishi','in_name'];
        $rows = $this->model->searchWhere($where)->select($fields)->page($page, $limit)
            ->orderByDesc('id')->get();
        return $this->returnMsg(200, '查询成功', $rows, $totalRows);
    }

//当前多少人购买
    public function swiperHasBuyer()
    {
        $x = [
            "赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈",
            "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许",
            "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏",
            "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章",
            "云", "苏", "潘", "葛", "奚", "范", "彭", "郎", "鲁", "韦",
            "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳",
            "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺",
            "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常",
            "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余",
            "元", "卜", "顾", "孟", "平", "黄", "和", "穆", "萧", "尹", "东方", "慕容", "毕"
        ];
        $cacheFile = "_swiperHasBuyer";
        $data = Cache::get($cacheFile);
        if (empty($data)) {
            shuffle($x);
            foreach (array_rand($x, 16) as $i => $key) {
                $data[] = [
                    'x' => $x[$key] . '*',
                    'm' => '/static/xh/avatar/comment-' . mt_rand(1, 30) . '.png',
                    't' => mt_rand(1, 30)
                ];
            }
            Cache::put($cacheFile, $data, 1800);
        }
        return $data;
    }

    //加入购物车人数
    public function hasBuyCartsNum($goodsId)
    {
        $cacheFile = "_hasBuyNum" . $goodsId;
        $nums = Cache::get($cacheFile);
        if (empty($nums)) {
            $nums = mt_rand(10, 50);
        }
        Cache::put($cacheFile, $nums, 1800);
        return $nums;
    }

    // 划分号码颜色
    public function splitNumberColorList($number, $sp)
    {
        $po = strpos($number, $sp);
        $pe = $po + strlen($sp);
        $result = [];
        $numberArr = str_split($number, 1);
        for ($i = 0; $i < count($numberArr); $i++) {
            $tmpArr = ['c' => 1, 'color' => '#444444', 's' => $numberArr[$i]];
            if ($i >= $po && $i < $pe) {
                $tmpArr = ['c' => 2, 'color' => '#ff0036', 's' => $numberArr[$i]];
            }
            $result[] = $tmpArr;
            if ($i == 2 || $i == 6) {
                $result[] = ['c' => 0, 'color' => '#c8c8c8', 's' => '-'];
            }
        }
        return $result;
    }

// 检测号码规则
    public function getNumberRule($number, $rules = [], $wishSymbol = '')
    {
        if (empty($rules)) {
            $rules = config('xh.ruleRegexp');
        }
        $ruleData = [];
        foreach ($rules as $symbol => $rule) {
            preg_match('/' . $rule . '/', $number, $tmp);
            if (!empty($tmp)) {
                if (!empty($wishSymbol) && $wishSymbol != $symbol) {
                    continue;
                }
                $ruleData['sp'] = $tmp[0];
                $ruleData['symbol'] = $symbol;
                break;
            }
        }
        if (!empty($ruleData['sp'])) {
            $ruleData['colors'] = $this->splitNumberColorList($number, $ruleData['sp']);
        }
        return $ruleData;
    }

    public function detail($id)
    {
        $where = [];
        $where['eq']['id'] = $id;
        $fields = ['id', 'detail_top_pic', 'detail_bg_color', 'xh_status', 'name', 'goods_price', 'goods_point', 'monthly', 'flow', 'voice', 'tishi', 'aperator AS operator', 'goods_detail', 'goods_remark','in_name'];
        $row = $this->model->searchWhere($where)->select($fields)->first()->toArray();
        if (!empty($row)) {
            $row['goods_remark'] = $this->setHtmlUploadPicHost($row['goods_remark']);
            $row['goods_detail'] = $this->setHtmlUploadPicHost($row['goods_detail']);
            $row['sale_price'] = $row['goods_price'];
            $row['booking'] = 1;
        }
        return $this->returnMsg(200, '查询成功', $row);
    }

    public function buy($params)
    {
        $goodsId = $params['goodsId'];
        $symbol = strtoupper(trim($params['symbol'] ?? ''));
        $result = $this->detail($goodsId);
        $detail = [];
        if ($result['code'] == 200) {
            $detail = $result['data'];
        }
        $phonesId = $params['id'] ?? 0;
        $fromApi = $params['fromApi'] ?? 0;
        if ($fromApi != 1) {
            $ModelPhones = new PhonesModel();
            $data = $ModelPhones->where(['id' => $phonesId])->select(['id', 'goods_id', 'number', 'operator', 'province', 'city', 'sale_price', 'booking'])->first()->toArray();
            if (is_object($detail)) {
                $detail = object2array($detail);
            }
            $detail = array_merge($detail, $data);
        }
        // 号码规则数据
        if (!empty($params['number'])) {
            $rules = $this->getNumberRule($params['number'], null, $symbol);
            $detail = array_merge($detail, $rules);
        }
        // 号码已购买
        $detail['swiperBuyer'] = $this->swiperHasBuyer();
        // 购物车
        $detail['carts'] = $this->hasBuyCartsNum($goodsId);
        // 公众号
        $detail['offical'] = 'xxxxx';
        return $this->returnMsg(200, '查询成功', $detail);
    }

    public function searchApiNumber($params, $page = 1, $limit = 10)
    {
        $apiSymbol = config('xh.apiSymbol');
        $symbol = strtoupper(trim($params['symbol'] ?? ''));
        $goodsId = intval($params['goodsId'] ?? 0);
        $priceMin = intval($params['priceMin'] ?? 0);
        $priceMax = intval($params['priceMax'] ?? 0);
        $sortType = intval($params['sort'] ?? 0);
        $operatorType = intval($params['operator'] ?? 0);
        $operatorName = '';
        if ($operatorType >= 0) {
            $operatorTypeList = config('card.operatorType');
            $operatorName = $operatorTypeList[$operatorType];
        }
        $isNot4 = intval($params['isNot4'] ?? 0);
        //模糊搜索的包含数字
        $likeNumber = trim($params['likeNumber'] ?? '');
        $exactNumber = trim($params['exactNumber'] ?? '');
        $provinceName = '';
        $cityName = trim($params['city'] ?? '');
        if ($cityName == '全国') {
            $cityName = '';
        }
        // 指定了商品
        $ModelGoods = new GoodsModel();
        $ModelProduct = new ProductModel();
        $ModelProductAddress = new SetAddressModel();
        $where = [];
        $where['eq']['a.status'] = 0;
        $where['eq']['b.status'] = 0;
        // 运营商
        if (!empty($operatorName)) {
            $where['eq']['a.aperator'] = $operatorName;
        }
        // 价格区间
        if ($priceMin + $priceMax > 0) {
            $where['raw'][] = "(a.goods_price>='" . $priceMin . "' AND a.goods_price<='" . $priceMax . "')";
        }
        //指定了商品还是指定城市
        if ($goodsId > 0) {
            $where['where']['a.id'] = $goodsId;
        } else {
            if (!empty($cityName)) {
                $where['like']['c.citys'] = $cityName;
            }
        }
        //  排序方式
        $sortField = 'goods_price';
        $sortMethod = 'asc';
        if ($sortType == 2) {
            $sortMethod = 'desc';
        }
        // 接口要用到的产品id
        $productId = 0;
        $fields = ['a.goods_price', 'a.product_id', 'a.product_code', 'a.goods_point', 'a.aperator AS operator', 'b.product_address', 'c.citys'];
        $row = $this->model->from($ModelGoods->getTable(), 'a')
            ->leftJoin($ModelProduct->getTable() . ' AS b', 'a.product_id', '=', 'b.id')
            ->leftJoin($ModelProductAddress->getTable() . ' AS c', 'b.product_address', '=', 'c.id')
            ->select($fields)
            ->searchWhere($where)->orderBy($sortField, $sortMethod)->first();
        if (!empty($row)) {
            $productId = $row['product_id'];
            //归属地
//            if (!empty($row['citys'])) {
//                $tmp = explode(',', $row['citys']);
//                $cityName = $tmp[0];
//            }
        }
        if (empty($productId)) {
            return $this->returnMsg(20, '无产品信息', []);
        }
// 模糊查找的数字变成尾号查
        if (!empty($likeNumber)) {
            $symbol = $likeNumber;
        } else if (!empty($exactNumber)) {
            // 精准查找要变成尾号,未4
            $digitArr = [];
            for ($i = 1; $i <= 10; $i++) {
                $digit = $exactNumber[$i];
                if ($digit != '*') {
                    $digitArr[] = $digit;
                }
            }
            if (!empty($digitArr)) {
                $symbol = implode('', $digitArr);
            }
        }
        // 尝试使用接口找
        $apiParams = [
            'id' => $goodsId,
//            'codeTypeCode' => 'AA',
//                'searchValue' => '123',
            'niceTag' => '1',
            'judgeType' => '0',
            'product_id' => $productId,
            'amounts' => '100'
        ];
        // 接口只提供尾部查找
        if (in_array($symbol, $apiSymbol)) {
            $apiParams['codeTypeCode'] = $symbol;
        } else if (is_numeric($symbol)) {
            $apiParams['searchValue'] = $symbol;
        }
        $apiGoodsRepository = new \App\Repository\Api\GoodsRepository();
        // 尝试拉5页来匹配
        $getN = empty($symbol) ? 1 : 5;
        //        正则指出靓号段
        $matchsRules = config('xh.ruleRegexp');
        $findData = [];
        for ($i = 0; $i < $getN; $i++) {
            $data = $apiGoodsRepository->getSelectNumberTwo($productId, $apiParams);
            if ($data['code'] == 200) {
                foreach ($data['data'] as $item) {
                    $rules = $this->getNumberRule($item['iccid'], $matchsRules, $symbol);
                    if (!empty($rules)) {
                        $findData[] = $item;
                    }
                }
            }
            // 每次找10个就好
            if (count($findData) >= 10) {
                break;
            }
            sleep(1);
        }
        $apiData = [];
        if (!empty($findData)) {
            // 多个也只取10个
            $findData = array_slice($findData, 0, 10);
            foreach ($findData as $k => $v) {
                $apiData[] = [
                    'id' => 0,
                    'goods_id' => $goodsId,
                    'number' => $v['iccid'],
                    'province' => $v['province'],
                    'city' => $v['city'],
                    'from_api' => 1,
                    'operator' => $row['operator'],
                    //接口号码只支持预约下单,即不用钱
                    'booking' => 1,
                    'sale_price' => $row['goods_price'] ?? 0
                ];
            }
        }
        unset($data, $row);
        return $this->returnMsg(200, '号码已查询', $apiData);
    }

//搜索号码
    public function searchNumber($params, $page = 1, $limit = 10)
    {
        $symbol = strtoupper(trim($params['symbol'] ?? ''));
        $goodsId = intval($params['goodsId'] ?? 0);
        $priceMin = intval($params['priceMin'] ?? 0);
        $priceMax = intval($params['priceMax'] ?? 0);
        $sortType = intval($params['sort'] ?? 0);
        $operatorType = intval($params['operator'] ?? 0);
        $operatorName = '';
        if ($operatorType >= 0) {
            $operatorTypeList = config('card.operatorType');
            $operatorName = $operatorTypeList[$operatorType];
        }
        $isEndNumber = intval($params['isEndNumber'] ?? 0);
        $isNot4 = intval($params['isNot4'] ?? 0);
        //模糊搜索的包含数字
        $likeNumber = trim($params['likeNumber'] ?? '');
        $exactNumber = trim($params['exactNumber'] ?? '');
        $provinceName = '';
        $cityName = trim($params['city'] ?? '');
        if ($cityName == '全国') {
            $cityName = '';
        }
        // 以上参数与searchApiNumber一样
        $apiData = [];
        $apiResult = $this->searchApiNumber($params, $page, $limit);
        // var_dump($apiResult,4444444444);
        if ($apiResult['code'] == 200) {
            $apiData = $apiResult['data'];
            $cityName = $apiData[0]['city'] ?? '';
        }
        //再找库存
        $where = [];
        $where['eq']['sale'] = 0;
        $where['eq']['status'] = 0;
        // 指定了商品
        if (!empty($goodsId)) {
            $where['eq']['goods_id'] = $goodsId;
        }
        // 指定了城市
        if (!empty($cityName)) {
            if (strpos($cityName, '市') !== false) {
                $where['eq']['city'] = $cityName;
            } else {
                $where['startLike']['city'] = $cityName;
            }
        }
//        $symbol = 'AAA';
        $ruleRegexp = config('xh.ruleRegexp');
        $sqlSymbol = config('xh.sqlSymbol');
//        模糊搜索
        if (!empty($likeNumber)) {
            if ($isEndNumber == 1) {
                $where['end_like']['number'] = $likeNumber;
            } else {
                $where['like']['number'] = $likeNumber;
            }
        } else if (!empty($exactNumber)) {
            //精确搜索
            $digitArr = [];
            for ($i = 1; $i <= 10; $i++) {
                $digit = $exactNumber[$i];
                if ($digit != '*') {
                    $digitArr[] = 't' . $i . '=' . $digit;
                }
            }
            if (!empty($digitArr)) {
                $where['raw'][] = '(' . implode(' AND ', $digitArr) . ')';
            }
        }
        if (isset($sqlSymbol[$symbol])) {
//            $where['REGEXP']['number'] = $ruleRegexp[$symbol];
            $where['raw'][] = $sqlSymbol[$symbol];
        } else if (is_numeric($symbol)) {
            if ($isEndNumber == 1) {
                $where['end_like']['number'] = $symbol;
            } else {
                $where['like']['number'] = $symbol;
            }
        }
        // 运营商
        if (!empty($operatorName)) {
            $where['eq']['operator'] = $operatorName;
        }
        // 价格区间
        if ($priceMin + $priceMax > 0) {
            $where['raw'][] = "(sale_price>='" . $priceMin . "' AND sale_price<='" . $priceMax . "')";
        }
        if ($isNot4 == 1) {
            $where['raw'][] = "(t10!=4 AND t9!=4 AND t8!=4 AND t7!=4 AND t6!=4 AND t5!=4 AND t4!=4 AND t3!=4 AND t2!=4 AND t1!=4)";
        }
        // 排序
        $sortField = 'sale_price';
        $sortMethod = 'asc';
        if ($sortType == 2) {
//            $sortField = 'sale_price';
            $sortMethod = 'desc';
        }
        $ModelPhones = new PhonesModel();
        $data = $ModelPhones->searchWhere($where)->select(['id', 'goods_id', 'number', 'operator', 'province', 'city', 'sale_price', 'booking'])->page($page, $limit)->orderBy($sortField, $sortMethod)->get()->toArray();
//        echo $this->getLastSql();
        if (empty($data)) {
            $data = [];
        }
        if (!empty($apiData)) {
            if (is_object($apiData)) {
                $apiData = object2array($apiData);
            }
            $data = array_merge($data, $apiData);
        }
//        正则指出靓号段
        $matchsRules = config('xh.ruleRegexp');
        foreach ($data as $k => $v) {
            if (!isset($v['from_api'])) {
                $v['from_api'] = 0;
            }
            $rules = $this->getNumberRule($v['number'], $matchsRules, $symbol);
            $v['sale_price'] = intval($v['sale_price']);
            $v = array_merge($v, $rules);
            $data[$k] = $v;
        }
        $noMore = 0;
        if (count($data) < $limit) {
            $noMore = 1;
        }
        // var_dump($data);
        return $this->returnMsg(200, $noMore, $data);
    }

    public function rulesRegexp($ruleType, $end = false, $regArray = null)
    {
        $regexp = "";
        if (empty($regArray)) {
            $regArray = config('xh.ruleRegexp');
        }
        if (isset($regArray[$ruleType])) {
            $regexp = $regArray[$ruleType];
        }
        if ($end) {
            $regexp = rtrim($regexp, '$') . '$';
        }
        return $regexp;
    }

//    手机号码匹配规则
    public function numberRule($number)
    {
        $result = ['symbol' => '', 'pattern' => ''];
        $regArray = config('xh.ruleRegexp');
        foreach ($regArray as $key => $reg) {
            preg_match('/' . $reg . '/', $number, $matches);
            if (!empty($matches)) {
                $result = ['symbol' => $key, 'pattern' => $matches[0]];
                break;
            }
        }
        return $result;
    }
}
